package com.chuantou.yuba.ui;

import java.util.HashMap;

import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.baidu.location.BDLocation;
import com.chuantou.yuba.R;
import com.chuantou.yuba.YBApp;
import com.chuantou.yuba.api.RequestManager;
import com.chuantou.yuba.api.UriHelper;
import com.chuantou.yuba.api.request.GsonRequest;
import com.chuantou.yuba.api.to.LoginTO;
import com.chuantou.yuba.api.to.UserTO;
import com.chuantou.yuba.api.to.WXResTO;
import com.chuantou.yuba.util.AccountManager;
import com.chuantou.yuba.util.ChatUtils;
import com.chuantou.yuba.util.Constants;
import com.chuantou.yuba.util.UiUtil;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

/**
 * 登录主界面
 * 
 * @author dl1001
 * 
 */
public class LoginActivity extends BaseActivity implements OnClickListener {
	private static final String TAG = LoginActivity.class.getName();
	public static final int ACTION_RETURN = 1;
	private EditText mPhoneView;
	private EditText mPasswordView;
	private boolean mIsLogin = false;
	private ProgressDialog mLoginDialog = null;
	private View mUseView;
	private int mAction;
	public static IWXAPI sWXApi;
	private static LoginActivity sActivity;
	private Tencent mTencent;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		sActivity = this;
		setContentView(R.layout.login);
		mAction = getIntent().getIntExtra(Constants.EXTRA_ACTION, -1);
		setupViews();
		sWXApi = WXAPIFactory.createWXAPI(this, Constants.WX_APP_ID, true);
		sWXApi.registerApp(Constants.WX_APP_ID);
		YBApp.sWXApi = sWXApi;
		mTencent = Tencent.createInstance(Constants.QQ_APP_ID, this);
		YBApp.get().startLocate(null);
	}

	private void setupViews() {
		mPhoneView = (EditText) findViewById(R.id.phone);
		mPasswordView = (EditText) findViewById(R.id.password);
		findViewById(R.id.forget_pwd).setOnClickListener(this);
		findViewById(R.id.regist).setOnClickListener(this);
		findViewById(R.id.login).setOnClickListener(this);
		findViewById(R.id.qq_login).setOnClickListener(this);
		findViewById(R.id.wx_login).setOnClickListener(this);
		mUseView = findViewById(R.id.use);
		mUseView.setOnClickListener(this);
		boolean useVisible = getIntent().getBooleanExtra(Constants.EXTRA_FORCE_LOGIN, true);
		mUseView.setVisibility(useVisible ? View.VISIBLE : View.GONE);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.forget_pwd: {
			Intent intent = new Intent(this, FindPasswordActivity.class);
			startActivity(intent);
		}
			break;
		case R.id.regist: {
			Intent intent = new Intent(this, RegistActivity.class);
			startActivity(intent);
		}
			break;
		case R.id.login:
			login();
			break;
		case R.id.qq_login:
			qqLoginClick();
			break;
		case R.id.wx_login:
			wxLoginClick();
			break;
		case R.id.use:
			Intent intent = new Intent(this, MainActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
			finish();
			break;
		default:
			break;
		}
	}

	private void login() {
		synchronized (TAG) {
			if (mIsLogin)
				return;
			String phone = mPhoneView.getText().toString().trim();
			if (TextUtils.isEmpty(phone) || phone.length() != 11) {
				Toast.makeText(getApplicationContext(), R.string.input_phone_error, Toast.LENGTH_SHORT).show();
				return;
			}
			String password = mPasswordView.getText().toString().trim();
			if (TextUtils.isEmpty(password)) {
				Toast.makeText(getApplicationContext(), R.string.input_password_error, Toast.LENGTH_SHORT).show();
				return;
			}
			mIsLogin = true;
			showLoginDialog();
			String url = UriHelper.getLoginUrl();
			HashMap<String, String> params = new HashMap<String, String>();
			params.put(UriHelper.PARAMS_MOBILE, phone);
			params.put(UriHelper.PARAMS_PASSWORD, password);
			BDLocation location = YBApp.get().getLocation();
			if (location != null) {
				params.put(UriHelper.PARAMS_POINT, location.getLongitude() + "," + location.getLatitude());
			}
			GsonRequest<LoginTO> request = new GsonRequest<LoginTO>(Method.POST, url, new Listener<LoginTO>() {

				@Override
				public void onResponse(LoginTO response) {
					if (!hasDestroyed()) {
						dismissLoginDialog();
						if (response == null) {
							Toast.makeText(getApplicationContext(), R.string.login_failed, Toast.LENGTH_SHORT).show();
						} else {
							if (response.isSuccess()) {
								UserTO user = response.getUser();
								user.setLoginTime(System.currentTimeMillis());
								AccountManager.saveUser(getApplicationContext(), user);
								// 没有昵称表示未完成注册第二步，需要完成补充个人资料
								if (TextUtils.isEmpty(user.getUsername())) {
									Intent intent = new Intent(LoginActivity.this, UpdateProfileActivity.class);
									startActivity(intent);
								} else {
									if (mAction == ACTION_RETURN) {
										setResult(RESULT_OK);
									} else {
										Intent intent = new Intent(LoginActivity.this, MainActivity.class);
										intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
										sendBroadcast(new Intent(Constants.INTENT_ACITON_LOGIN));
										startActivity(intent);
									}
									ChatUtils.loginIM(LoginActivity.this);
								}
								finish();
							} else {
								String msg = response.getMsg();
								msg = TextUtils.isEmpty(msg) ? getString(R.string.login_failed) : msg;
								Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
							}
						}
					}
				}
			}, new ErrorListener() {

				@Override
				public void onErrorResponse(VolleyError error) {
					if (!hasDestroyed()) {
						dismissLoginDialog();
						Toast.makeText(getApplicationContext(), R.string.login_failed, Toast.LENGTH_SHORT).show();
					}
				}
			}, params, LoginTO.class);
			RequestManager.startRequest(getApplicationContext(), request);
		}
	}

	IUiListener mQQListener = new IUiListener() {

		@Override
		public void onError(UiError arg0) {

		}

		@Override
		public void onComplete(Object response) {
			try {
				if (response != null) {
					JSONObject object = (JSONObject) response;
					if (object.has("openid")) {
						String openid = object.getString("openid");
						showLoginDialog();
						onThirdLpgin(openid, Constants.PLATFORM_QQ);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		@Override
		public void onCancel() {

		}
	};

	private void qqLoginClick() {
		if (UiUtil.isFastDoubleClick())
			return;
		mTencent.login(this, "all", mQQListener);
	}

	private void wxLoginClick() {
		if (UiUtil.isFastDoubleClick())
			return;
		final SendAuth.Req req = new SendAuth.Req();
		req.scope = "snsapi_userinfo";
		req.state = "fishbar_login";
		sWXApi.sendReq(req);
	}

	private void requestWXOpenId(String code) {
		synchronized (TAG) {
			if (mIsLogin)
				return;
			mIsLogin = true;
			showLoginDialog();
			String url = UriHelper.getWXTokenUrl(Constants.WX_APP_ID, Constants.WX_APP_SECRET, code);
			HashMap<String, String> params = new HashMap<String, String>();
			GsonRequest<WXResTO> request = new GsonRequest<WXResTO>(Method.GET, url, new Listener<WXResTO>() {
				@Override
				public void onResponse(WXResTO response) {
					if (!hasDestroyed()) {
						if (response == null || TextUtils.isEmpty(response.getOpenid())) {
							dismissLoginDialog();
							Toast.makeText(getApplicationContext(), R.string.login_failed, Toast.LENGTH_SHORT).show();
						} else {
							onThirdLpgin(response.getOpenid(), Constants.PLATFORM_WX);
						}
					}
				}
			}, new ErrorListener() {

				@Override
				public void onErrorResponse(VolleyError error) {
					if (!hasDestroyed()) {
						dismissLoginDialog();
						Toast.makeText(getApplicationContext(), R.string.login_failed, Toast.LENGTH_SHORT).show();
					}
				}
			}, params, WXResTO.class);
			RequestManager.startRequest(getApplicationContext(), request);
		}
	}

	private void onThirdLpgin(String openId, String platform) {
		GsonRequest<LoginTO> request = RequestManager.getThirdLoginRequest(new Listener<LoginTO>() {

			@Override
			public void onResponse(LoginTO response) {
				if (!hasDestroyed()) {
					dismissLoginDialog();
					if (response == null) {
						Toast.makeText(getApplicationContext(), R.string.login_failed, Toast.LENGTH_SHORT).show();
					} else {
						if (response.isSuccess()) {
							UserTO user = response.getUser();
							user.setLoginTime(System.currentTimeMillis());
							AccountManager.saveUser(getApplicationContext(), user);
							// 没有昵称表示未完成注册第二步，需要完成补充个人资料
							if (TextUtils.isEmpty(user.getUsername())) {
								Intent intent = new Intent(LoginActivity.this, UpdateProfileActivity.class);
								startActivity(intent);
							} else {
								if (mAction == ACTION_RETURN) {
									setResult(RESULT_OK);
								} else {
									Intent intent = new Intent(LoginActivity.this, MainActivity.class);
									intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
									sendBroadcast(new Intent(Constants.INTENT_ACITON_LOGIN));
									startActivity(intent);
								}
								ChatUtils.loginIM(LoginActivity.this);
							}
							finish();
						} else {
							String msg = response.getMsg();
							msg = TextUtils.isEmpty(msg) ? getString(R.string.login_failed) : msg;
							Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
						}
					}
				}

			}
		}, new ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {
				if (!hasDestroyed()) {
					dismissLoginDialog();
					Toast.makeText(getApplicationContext(), R.string.login_failed, Toast.LENGTH_SHORT).show();
				}
			}
		}, platform, openId);
		RequestManager.startRequest(getApplicationContext(), request);
	}

	private void showLoginDialog() {
		if (mLoginDialog != null && mLoginDialog.isShowing()) {
			return;
		}
		mLoginDialog = new ProgressDialog(this);
		mLoginDialog.setCancelable(false);
		mLoginDialog.setMessage(getString(R.string.logining));
		mLoginDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {

			@Override
			public void onDismiss(DialogInterface dialog) {
				mIsLogin = false;
			}
		});
		mLoginDialog.show();
	}

	private void dismissLoginDialog() {
		if (mLoginDialog != null && mLoginDialog.isShowing()) {
			mLoginDialog.dismiss();
		}
	}

	public static void onWXLoginCallback(String code) {
		if (sActivity != null && !sActivity.hasDestroyed()) {
			sActivity.requestWXOpenId(code);
		}
	}

	public static void start(Activity activity, int requestCode, int action) {
		Intent intent = new Intent(activity, LoginActivity.class);
		intent.putExtra(Constants.EXTRA_ACTION, action);
		intent.putExtra(Constants.EXTRA_FORCE_LOGIN, true);
		if (requestCode > 0) {
			activity.startActivityForResult(intent, requestCode);
		} else {
			activity.startActivity(intent);
		}
	}

	public static void start(Fragment fragment, int requestCode, int action) {
		Intent intent = new Intent(fragment.getActivity(), LoginActivity.class);
		intent.putExtra(Constants.EXTRA_ACTION, action);
		intent.putExtra(Constants.EXTRA_FORCE_LOGIN, true);
		if (requestCode > 0) {
			fragment.startActivityForResult(intent, requestCode);
		} else {
			fragment.startActivity(intent);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		mTencent.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	protected void onDestroy() {
		sActivity = null;
		YBApp.get().stopLocate(false);
		super.onDestroy();
	}

	@Override
	public void onBackPressed() {
		finish();
	}
}
